// 生成随机颜色
function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

// 调整颜色亮度的函数
function shadeColor(color, percent) {
	// 将颜色转换为RGB
	let Rgb = hexToRgb(color);
	let {
		r,
		g,
		b
	} = Rgb
	let p = percent < 0 ? percent * -1 : percent
	// 计算亮度调整后的RGB值
	r = Math.round(Math.min(255, r + p / 100 * 255, 255))
	g = Math.round(Math.min(255, g + p / 100 * 255, 255))
	b = Math.round(Math.min(255, b + p / 100 * 255, 255))
	return `rgb(${r}, ${g}, ${b})`;
}
// 调整颜色饱和度的函数
function desaturateColor(color, percent) {
	let Rgb = hexToRgb(color);
	let {
		r,
		g,
		b
	} = Rgb;
	let gray = Math.round((r + g + b) / 3);
	return `rgb(${r + (gray - r) * percent / 100}, ${g + (gray - g) * percent / 100}, ${b + (gray - b) * percent / 100})`;
}
// 十六进制颜色转换为RGB对象的函数
function hexToRgb(hex) {
	let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
	return result ? {
		r: parseInt(result[1], 16),
		g: parseInt(result[2], 16),
		b: parseInt(result[3], 16)
	} : null;
}
//根据主色调自动生成反色
function contrastingColor(color) {
	// 转换16进制颜色到RGB
	let rgb = color.match(/\w\w/g).map(hex => parseInt(hex, 16));
	// 计算反色的RGB值
	let contrasting = rgb.map(channel => 255 - channel);
	//返回rgb格式
	return `rgb(${contrasting[0]}, ${contrasting[1]},${contrasting[2]})`;
	//返回16进制格式
	return '#' + contrasting.map(channel => channel.toString(16).padStart(2, '0')).join('');
}
//js生成相近色颜色RGB
function similarColor(color) {
	let Rgb = hexToRgb(color);
	//找到最大的色值
	let maxColorObject = findMaxRGB(Rgb.r, Rgb.g, Rgb.b)
	//生成相近色
	let shallowColorArray = getShallowRGB(maxColorObject, Rgb.r, Rgb.g, Rgb.b)
	return [
		`rgb(${shallowColorArray[0].toString()})`,
		`rgb(${shallowColorArray[1].toString()})`,
		`rgb(${shallowColorArray[2].toString()})`
	]
}

function getShallowRGB(maxColorObject, R, G, B) {
	let threshold = 30 //色阶偏差值
	let offset = 10 //色深偏差值
	let result = []
	for (var d in maxColorObject) {
		if (d == 'R') {
			result = [
				[R - offset, G + threshold, B + threshold],
				[R - offset, G + threshold + 20, B + threshold + 20],
				[R - offset, G + threshold + 40, B + threshold + 40]
			]
		} else if (d == 'G') {
			result = [
				[R + threshold, G - offset, B + threshold],
				[R + threshold + 20, G - offset, B + threshold + 20],
				[R + 60, G - offset, B + 60]
			]
		} else if (d == 'B') {
			result = [
				[R + threshold, G + threshold, B - offset],
				[R + threshold + 20, G + threshold + 20, B - offset],
				[R + threshold + 40, G + threshold + 40, B - offset]
			]
		}
	}
	return result
}
//找到最大的RGB
function findMaxRGB(R, G, B) {
	let max
	let index
	if (R >= G && R >= B) {
		max = R
		index = 'R'
	}
	if (G >= R && G >= B) {
		max = G
		index = 'G'
	}
	if (B >= R && B >= G) {
		max = B
		index = 'B'
	}
	return {
		[index]: max
	}
}


export {
	getRandomColor,
	hexToRgb,
	shadeColor,
	desaturateColor,
	contrastingColor,
	similarColor
}